package com.example.servlet;

import com.example.bean.Messages;
import com.example.dao.MessagesDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//Servlet处理 HTTP 请求
@WebServlet(name = "AddMessageServlet", value = "/AddMessageServlet")
public class AddMessageServlet extends HttpServlet {
    // doPost方法:是HttpServlet 类中的一个方法，用于处理 HTTP POST 请求
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset:utf-8");//设置响应的内容类型为 HTML
        request.setCharacterEncoding("utf-8");
        // 读取参数值
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        MessagesDao messagesDao = new MessagesDao();
        //调用 MessagesDao 的 addMessage 方法，尝试将新的留言添加到数据库。flag 用于存储操作的结果，通常表示操作成功或失败
        int flag = messagesDao.addMessage(new Messages(author, content));
        if (flag < 0) {
            request.setAttribute("info", "留言失败，请联系管理员");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        } else {
            request.setAttribute("info", "留言成功");
            request.getRequestDispatcher("AddMessage.jsp").forward(request, response);
        }
    }
}
